<template>
    <el-form ref="form" :model="formData" label-width="80px" v-loading="showLoading">
		<el-form-item label="用户昵称" prop="userNickName" verify>
			<el-input
				class="formItem"
				v-model="formData.userNickName"
				maxlength="20"
				placeholder="请设置昵称"></el-input>
			<span class="describe">长度不超过30</span>
		</el-form-item>
		<template v-if="!isEdit">
			<el-form-item label="账号" prop="userAccountName" verify>
				<el-input
					class="formItem"
					v-model="formData.userAccountName"
					maxlength="20"
					placeholder="请设置账号">
				</el-input>
				<span class="describe">长度不超过20</span>
			</el-form-item>

			<el-form-item label="登录密码" v-if="!isEdit" prop="userPassword" verify>
				<el-input
					class="formItem"
					v-model="formData.userPassword"
					maxlength="20"
					placeholder="请设置密码"
					type="password">
				</el-input>
				<span class="describe">长度不低于6位</span>
			</el-form-item>
		</template>
		<template v-else>
			<el-form-item verify label="设置头像" prop="userHeadImageUrl">
				<p class="describe">提示：本地上传图片大小不能超过2M【图片尺寸比例建议：(1:1)】</p>
				<el-upload
					:action="upImgUrl"
					:data="access_token"
					:show-file-list="false"
					:before-upload="beforeAvatarUpload"
					:on-success="uploadSuccess">
					<img v-if="formData.userHeadImageUrl" :src="formData.userHeadImageUrl" class="avatar" />
					<i v-else class="el-icon-plus avatar-uploader-icon"></i>
					<el-input class="inputs none imgArea" v-model="formData.userHeadImageUrl"></el-input>
				</el-upload>
			</el-form-item>

			<el-form-item label="新密码" prop="newPassword" verify>
				<el-input
					class="formItem"
					v-model="formData.newPassword"
					maxlength="20"
					placeholder="请设置新密码"
					type="password">
				</el-input>
				<span class="describe">长度不低于6位</span>
			</el-form-item>
		</template>

		<el-form-item label="选择角色" verify prop="roleIds">
			<el-select
				class="formItem"
				v-model="formData.roleIds"
				placeholder="选择角色"
				multiple
				collapse-tags
				@change="checkRole">
				<el-option
					v-for="item in rolesList"
					:key="item.roleId"
					:label="item.roleName"
					:value="item.roleId">
				</el-option>
			</el-select>
		</el-form-item>

		<el-form-item class="flex-center margin_top_30" style="margin-bottom: 0">
			<el-button type="primary" @click="addUser">确 认</el-button>
			<el-button  @click="cancelAdd">取 消</el-button>
		</el-form-item>
	</el-form>
</template>

<script>
    import {
        userInfo,
        userAdd,
        userUpdate,
		roleList,
		userInfoAndRoles
    } from "@/api/table";
    export default {
        name: "USER_ADD",
        components: {},
        data() {
            return {
                formData:{},
                isEdit: false,
                //上传图片所需
                upImgUrl: process.env[this.$base] + "/medias/image/upload",
                access_token: {
                    access_token: this.$store.getters.token
                },
                showLoading: false
            }
        },
        props: {
			infos: {
				type: Object,
				default() {
					return {}
				}
			},
			rolesList: {
				type: Array,
				default() {
					return []
				}
			},
		},
        methods: {
			async updateData() {
				this.formData = {...this.infos};
				const { userId } = this.formData;
				if (userId) {
					this.isEdit = true;
					await userInfoAndRoles({ userId }).then(res => {
						if(res.code == 200){
							this.$set(this.formData, 'roleIds', res.data.data.roles)
						}
					}).catch(err => {});
				}
			},
            //上传图片
            beforeAvatarUpload(file) {
                var type = "image/jpg,image/jpeg,image/png,image/gif";
                const isJPG = type.indexOf(file.type) != -1;
                const isLt2M = file.size / 1024 / 1024 < 2;

                if (!isJPG) {
                    this.$message.error("上传图片只能是 JPG,JPEG,PNG,GIF 格式!");
                }
                if (!isLt2M) {
                    this.$message.error("上传图片大小不能超过 2MB!");
                }
                return isJPG && isLt2M;
            },
            uploadSuccess(response, file, fileList) {
                if (response.code == "200") {
					this.$set(this.formData, 'userHeadImageUrl', fileUrl);
                }
            },
            checkRole() {
                console.log(this.formData.roleIds===[]?'':this.formData.roleIds.join(","));
            },
            //添加用户
            addUser() {
                this.$refs['form'].validate((valid) => {
					if(valid) {
						const {
							userHeadImageUrl,
							userNickName,
							userPassword,
							newPassword,
							userAccountName,
							roleIds,
							userId
						} = this.formData;

						this.showLoading = true;
						// 修改
						if (userId) {
							userUpdate({
								userId,
								roleIds: roleIds.join(","),
								headPath: userHeadImageUrl,
								userNickName,
								password: userPassword,
								newPassword
							}).then(res => {
								if (res.code !== 200) {
									this.$message.error(res.description);
									return
								}
								this.$message.success("修改成功");
								setTimeout(() => {
									this.$emit('func', {refresh: true});
								}, 0);
							}).finally(_ => {
								this.showLoading = false
							})
							return
						}
						
						// 新增
						userAdd({
							userName: userAccountName,
							password: userPassword,
							userNickName,
							roleIds: roleIds.join(","),
						}).then( res => {
							if (res.code !== 200) {
								this.$message.error(res.description);
								return
							}
							this.$message.success("新增成功");

							setTimeout(() => {
								this.$emit('func', {refresh: true});
							}, 0);
						}).finally(_ => {
							this.showLoading = false
						});
					}
				});
            },
            cancelAdd(){
                this.$emit('func')
            },
        },
    }
</script>

<style lang="scss" scoped>
  .formItem {
    width: 360px;
  }
  .describe {
    color: #999;
    margin-left: 10px;
  }

</style>
